package com.xyy.saas.payment.adpater.jd.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;

public class JDAES {
    public static String AES = "AES"; // optional value JDAES/DES/DESede

    public static String CIPHER_ALGORITHM = "AES"; // optional value JDAES/DES/DESede

    public static int KEY_SIZE = 128; //AES使用长度为128位的秘钥

    public static Key getSecretKey(String key) throws Exception {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(key.getBytes());
        KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);
        // 使用128位长度的秘钥
        keyGenerator.init(KEY_SIZE, random);
        return keyGenerator.generateKey();
    }

    public static byte[] encrypt(String data, String key, String charset) throws Exception {
        Key secretKey = getSecretKey(key);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return cipher.doFinal(data.getBytes(charset));
    }

    public static String decrypt(byte[] data, String key, String charset) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        Key secretKey = getSecretKey(key);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(data), charset);
    }

    public static String decryptBase64(String data, String key, String charset) throws Exception {
        return decrypt(Base64.decodeBase64(data.getBytes(charset)), key, charset);
    }

}
